//
//  HzVC.swift
//  Auscultation
//
//  Created by 来 on 2020/11/28.
//

import UIKit

class HzVC: BaseVC {

    var hzs: UILabel!
    var collectionView: UICollectionView!
    
    var dataArray: [[String: Any]] = []
    var pageNum: Int = 1
    var pageSize: Int = 10
    var keyWord: String = ""
    var gender: String = ""
    
    var sx_state: Int = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()

        initUI()
        loadData()
        collectionView.mj_header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(loadData))
        collectionView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingTarget: self, refreshingAction: #selector(loadMoreData))
        NotificationCenter.default.addObserver(self, selector: #selector(HzVC.loadData), name: NSNotification.Name(rawValue: "ReloadHzVC"), object: nil)
    }
    
    // 数据刷新
    @objc func loadData() {
        pageNum = 1
        dataArray.removeAll()
        loadMoreData()
    }
    @objc func loadMoreData() {
        let paramet: [String: String] = [
            "keyWord": keyWord,
            "gender": gender,
            "pageNo" : pageNum.description,
            "pageSize" : pageSize.description
        ]
        EWERequest.lgf("patient", paramet, .get) { [weak self] (data) in
            let result = (data["result"] as? [[String: Any]]) ?? []
            if result.count > 0 {
                self?.dataArray += result
                self?.pageNum += 1
            }
            self?.collectionView.reloadData()
            self?.endRefreshing()
            if result.count == 0 {
                self?.collectionView.mj_footer?.endRefreshingWithNoMoreData()
            }
        } _: { [weak self] (error) in
            SVProgressHUD.showError(error)
            self?.endRefreshing()
        }
    }
    func endRefreshing() {
        self.collectionView.mj_header?.endRefreshing()
        self.collectionView.mj_footer?.endRefreshing()
    }

    // 新建患者
    @objc func s_xjhz(_ sender: UITapGestureRecognizer) {

        self.navigationController?.pushViewController(XjhzVC(), animated: true)
    }
    
    @objc func s_sx(_ sender: UITapGestureRecognizer) {
        SxV().showIn(self.view, ["状态"], ["状态": ["男", "女"]], [self.sx_state]) { [weak self] (sxv, name, state) in
            if state.first == 0 {
                self?.gender = ""
            } else {
                self?.gender = state.first!.description
            }
            if self?.sx_state != state.first {
                self?.loadData()
            }
            self?.sx_state = state.first ?? 0
        }
    }
    
}

extension HzVC: UITextFieldDelegate {
    func textFieldDidEndEditing(_ textField: UITextField) {
        keyWord = textField.text ?? ""
        loadData()
    }
}

extension HzVC : UICollectionViewDelegateFlowLayout, UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize  {
        return CGSize.init(width: UIDevice.lgf_ScreenW, height: 110)
    }
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataArray.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.lgf_DequeueReusableCell(with: HzCell.self, for: indexPath)
        cell.tx.lgf_setImage((dataArray[indexPath.item]["avatar"] as? String) ?? "")
        cell.mz.text = (dataArray[indexPath.item]["name"] as? String) ?? ""
        cell.sj.text = (dataArray[indexPath.item]["phone"] as? String) ?? ""
        cell.sg.text = (dataArray[indexPath.item]["guardian"] as? String) ?? ""
        cell.nl.text = ((dataArray[indexPath.item]["birthday"] as? Int) ?? 0).description.lgf_TimeStampToDate().lgf_AgeWithDateOfBirth().description + "岁"
        let lastTime = (dataArray[indexPath.item]["lastTime"] as? String) ?? ""
        if lastTime == "没有新数据" {
            cell.status_l.text = (dataArray[indexPath.item]["lastTime"] as? String) ?? ""
            cell.status.backgroundColor = UIColor.init(lgf_HexString: "6E99BF")
            cell.xsj.isHidden = true
            cell.xsj.snp.updateConstraints { (make) in
                make.width.equalTo(0)
            }
        } else {
            cell.status_l.text = ((dataArray[indexPath.item]["lastTime"] as? String) ?? "") + "日内"
            cell.status.backgroundColor = UIColor.init(lgf_HexString: "00C9F4")
            cell.xsj.isHidden = false
            cell.xsj.snp.updateConstraints { (make) in
                make.width.equalTo(50)
            }
        }
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let vc = HzxqVC()
        vc.id = (dataArray[indexPath.item]["id"] as? String) ?? ""
        let lastTime = (dataArray[indexPath.item]["lastTime"] as? String) ?? ""
        if lastTime == "没有新数据" {
            vc.type = 1
        } else {
            vc.type = 2
        }
        self.navigationController?.show(vc, sender: self)
    }
}
